<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Create and Define some functions for global use
 *
 * @author Samuel Pulta
 */
class Functions extends Library{

		// Limit Text
		public static function truncateStringWords($str, $maxlen){
				if (strlen($str) <= $maxlen) return $str;
		
				$newstr = substr($str, 0, $maxlen);
				if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
		
				return $newstr . "....";
		}
		
		
		// Abbreviate string
    public function initials($str) {
        $ret = '';
        foreach (explode(' ', $str) as $word)
            $ret .= strtoupper($word[0]);
        return $ret;
    }
		

		// Generate Random chars
		
		public function random_chars($limit){
				$random = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,$limit);
				
				return $random;
		}
		
		public function str_remove_regex_char($db,$db_name,$auth,$page_name){
				
				$Role_Access = $db->query("SELECT * FROM " . $db->tbl_name($db_name) . " WHERE level_id = {$db->escape($auth['level_id'])}
				AND page_access = {$db->escape($page_name)}","row");
				$remove_sp_char = str_replace("[", "", $Role_Access['access_type']);
				$remove_sp_char = str_replace('\"', "", $remove_sp_char);
				$remove_sp_char = str_replace('\"', "", $remove_sp_char);
				$remove_sp_char = str_replace("]", "", $remove_sp_char);
				
				$str = explode(",",$remove_sp_char);
				$count = count($str);
				$access = $str[$count-1];
				
				if($access == "None"){
						return array("display" 	=> " display:none ",
														"access"		=> $access);
				}else{
						return array("display" 	=> " display:block ",
														"access"		=> $access);
				}
				
				
		}
    
		/* Base Encode / Decode
    /* ====================================================================================== */
    
    public function base_encode_decode($action, $string) {
        if ($action == "encrypt") {
            $encode = base64_encode(base64_encode(base64_encode(base64_encode($string))));
            return $encode;
        } elseif ($action == "decrypt") {
            $decode = base64_decode(base64_decode(base64_decode(base64_decode($string))));
            return $decode;
        }
    }
    
    
    /* Select parameter module
    /* ====================================================================================== */
    
    public function url_module($parameter){
        $module = $this->curPageURL("module_parameter");
        $split_module = explode("/",$module);
        if(isset($split_module[$parameter])){
            return $split_module[$parameter];
        }
    }
    
    /* Get Module
    /* ====================================================================================== */
    
    public function get_module($name,$parameter){
        $module = $this->curPageURL("module_parameter");
        $split_module = explode("/",$module);
        
        if(isset($split_module[$parameter])){
            if($split_module[$parameter] == $name){
                if($parameter == "0"){
                    $return = 'active';
                }else{
                    $return = 'active_navigation_navigation_a';
                }
            }else{
                $return = '';
            }
        }else{
            $return = '';
        }
        
        
        return $return;
    }
    
    /* Set Format
    /* ====================================================================================== */
    
    public function set_date_format($date){
        $date_format = new DateTime($date);
        $date_time = $date_format->format('g:i a \o\n\ l jS F Y');
        $date = $date_format->format("F j, Y");
        $time = $date_format->format('g:i A');
        
        return array("date_time"    =>  $date_time,
                     "date"         =>  $date,
                     "time"         =>  $time);
    }
    
    /* Set default Time
    /* ====================================================================================== */
    
    public function set_default_timezone_datetime(){
        $timezone = "Asia/Manila";
		if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
        $date = date('Y-m-d');
        $time = date('H:i:s');
        $date_time = date('Y-m-d H:i:s');
        
        return array("date"     =>  $date,
                     "time"     =>  $time,
                     "date_time" =>  $date_time);
    }
    
    /* Save Audit logs for every action of the user 
    /* ====================================================================================== */
    
    public function save_audit_logs($db,$auth_id,$action_id,$table_name,$date_time,$record_id){
        $audit_logs = new Audit_Logs($db,$auth_id);
        
        $audit_logs->user_id = $auth_id;
        $audit_logs->audit_action = $action_id;
        $audit_logs->table_name = $table_name;
        $audit_logs->record_id = $record_id;
        $audit_logs->ip_address = $_SERVER['REMOTE_ADDR'];
        $audit_logs->date = $date_time;
        $audit_logs->is_active = "1";
        
        $audit_logs->save();
    }
    
    /* Get lat and long by address         
    /* ====================================================================================== */
    
    public function geo_location($ip){
        if($ip != "127.0.0.1"){
            $address = $ip; // Google HQ
            $prepAddr = str_replace(' ','+',$address);
            $geocode= file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
            $output= json_decode($geocode);
            $latitude = $output->results[0]->geometry->location->lat;
            $longitude = $output->results[0]->geometry->location->lng;
            
            $geolocation = json_encode(array(
                                    "latitude"  =>  $latitude,
                                    "longitude" =>  $longitude
                                    ));
            
            return $geolocation;
        }
        
    }
    
    /* Save Visitors IP
    /* ====================================================================================== */
    
    public function visitors_ip(){
        // Required database tb_visitors
        $date_time = date('Y-m-d H:i:s');
        $db = new Database();
        $ip = $_SERVER["REMOTE_ADDR"];
        
        $geo_loc = json_decode($this->geo_location($ip),true);
        
        $visitors = new Visitors($db,$ip);
        
            $visitors->lat_coordinate = $geo_loc['latitude'];
            $visitors->long_coordinate = $geo_loc['longitude'];

        // validate if ip is on the db already
        if($ip == $visitors->ip){
            $visitors->ip = $ip;
            $visitors->visit_times = $visitors->visit_times + 1;
            $visitors->date_last_visited = $visitors->date_visited;
            $visitors->date_visited = $date_time;
            $visitors->update();
        }else{
            $visitors->ip = $ip;
            $visitors->visit_times = "1";
            $visitors->date_last_visited = $date_time;
            $visitors->date_visited = $date_time;
            $visitors->is_active = "1";
            $visitors->save();
        }
        
    }
   
    /* Arrange json formatter
    /* for better viewing of json_encode
    /* ====================================================================================== */

    public function view_json_formatter($string) {
        $pattern = array(',"', '{', '}');
        $replacement = array(",\n\t\"", "\n{\n\t", "\n}");
        return str_replace($pattern, $replacement, $string);
    }
    
    /* Create Unique ID  */
    /* ====================================================================================== */
    
    public function create_unique_id($a){
        $unique_id = date('H:i:s') . time() . uniqid() * time() * date("Y") . date("Y") . date('H:i:s');
        $id = $this->encrypt_decrypt("encrypt", $unique_id . $a);
        return $id;
    }
    
    /* Get Location from DB  */
    /* ====================================================================================== */
    public function get_location($db,$tabindex){
        $query = $db->query("SELECT * FROM tb_location","array");
        $ret = "";
        
        $ret .= '<select id="city_provincial_address" name="city_provincial_address" data-placeholder="City and Provincial Address" class="select-multiple" tabindex="'.$tabindex.'">';
            $ret .= '<option value=""></option>';
            foreach($query as $list){
                $ret .= '<option value="' . $list['id'] . '">' . $list['city'] . '</option>';
            }
        $ret .= '</select>';
        
        return $ret;
    }
    
    /* Generate Year  */
    /* ====================================================================================== */
    
        public function generate_year(){
            $ret = "";
            for($a = 1960; $a <= date("Y"); $a++){
                $ret .= '<option value="' . $a . '">' . $a . '</option>';
            }
            return $ret;
        }
    
    /* Send Email Via PHP Mailer  */
    /* optional, gets called from within class.phpmailer.php if not already loaded  */
    /* the true param means it will throw exceptions on errors, which we need to catch  */
    /* ====================================================================================== */

        public function sendEmail_smtp($body, $to = array(), $cc = array(), $bcc = array(), $from, $from_title, $mail_title) {
    
            $mail = new PHPMailer(true);
    
            $mail->IsSMTP(); // telling the class to use SMTP
    
            try {
                $mail->Host = 'mail.gmail.com';     // SMTP server
                $mail->SMTPDebug = 2;               // enables SMTP debug information (for testing)
                $mail->SMTPAuth = true;             // enable SMTP authentication
                $mail->SMTPSecure = "ssl";          // sets the prefix to the servier
                $mail->Host = 'smtp.gmail.com';     // sets GMAIL as the SMTP server
                $mail->Port = 465;                  // set the SMTP port for the GMAIL server
                $mail->Username = "samuel282@gmail.com";  // GMAIL username
                $mail->Password = "Pult@F@m1ly";            // GMAIL password
                // To
                foreach ($to as $email => $name) {
                    $mail->AddAddress($email, $name);
                }
                // CC
                foreach ($cc as $email => $name) {
                    $mail->addCC($email, $name);
                }
                // BCC
                foreach ($bcc as $email => $name) {
                    $mail->addBCC($email, $name);
                }
    
                //$mail->AddAddress('samuel_boa2000@yahoo.com', 'Samuel Pulta');
                $mail->SetFrom($from, $from_title);
                //$mail->AddReplyTo('ervinne.sodusta@gs3.com.ph', 'Ervinne Sodusta');
                $mail->Subject = $mail_title;
                //$mail->AddCC('admin@example.com', 'Example.com');
                //$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
    
    
                $mail->MsgHTML($body);
                //$mail->AddAttachment('images/phpmailer.gif');      // attachment
                //$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
                ob_start();
                $mail->Send();
                ob_get_clean();
    
                //return "Message Sent OK</p>\n";
            } catch (phpmailerException $e) {
    
                //echo $e->errorMessage(); //Pretty error messages from PHPMailer
            } catch (Exception $e) {
    
                //echo $e->getMessage(); //Boring error messages from anything else!
            }
        }
        
    
    /* User to encrypt any variable and decrypt it */
    /* ====================================================== */
    
        public function encrypt_decrypt($action, $string) {
            $output = false;
    
            //$key = 'GLOBALSTRATEGICSOLUTIONANDSERVICESINC_FORMALISTICS';
            $key = 'MyNaturalSuperStrongRandomKey';
        
            // initialization vector 
            $iv = md5(md5(md5($key)));
    
            if ($action == 'encrypt') {
                $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5(md5(md5($key))), $string, MCRYPT_MODE_CBC, md5(md5(md5($iv))));
                $output = base64_encode($output);
            } else if ($action == 'decrypt') {
                $output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5(md5(md5($key))), base64_decode($string), MCRYPT_MODE_CBC, md5(md5(md5($iv))));
                $output = rtrim($output);
            }
            return $output;
        }
        
    /* Get Url of the page */
    /* ====================================================== */
    
        public function curPageURL($params) {
            $pageURL = 'http';
            $pageURL .= "://";
            if ($params == "?") {
                $par = $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
                $par = explode("?", $par);
                $pageURL .= $par[0];
            } elseif ($params == "") {
                if ($_SERVER["HTTPS"] == "on") {
                    $pageURL .= "s";
                }
                if ($_SERVER["SERVER_PORT"] != "80") {
                    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
                } else {
                    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
                }
            } elseif ($params == "module") {
                if ($_SERVER["HTTPS"] == "on") {
                    $pageURL .= "s";
                }
                if ($_SERVER["SERVER_PORT"] == "80") {
                    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
                } else {
                    $pageURL = substr($_SERVER["REQUEST_URI"], 1);
                    // $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
                }
            } elseif ($params == "module_parameter") {
                $pageURL = substr($_SERVER["REQUEST_URI"], 1);
            } elseif ($params == "serverName") {
                $pageURL .= $_SERVER["SERVER_NAME"];
            } elseif ($params == "port") {
                $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
            } elseif ($params == "baseuri") {
                if ($_SERVER["HTTPS"] == "on") {
                    $pageURL .= "s";
                }
                if ($_SERVER["SERVER_PORT"] != "80") {
                    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
                } else {
                    $pageURL .= $_SERVER["SERVER_NAME"];
                }
            }
    
            return $pageURL;
        }
        
    /* Encode and Decode URL */
    /* ====================================================== */
    
        public function encode_decode_url($url,$type){
            if($type=="encode"){
                return urlencode($url);
            }else{
                return urldecode($url);
            }
        }
        
    /* URL REDIRECT  */
    /* ====================================================== */
        
        public function url_redirect(){
            $current_url = $this->encode_decode_url($this->curPageURL("module_parameter"),"encode");

            $url = $_SERVER['REQUEST_URI'];
            if($url!=""){
                header('location: /login?redirect_url=' . $current_url);
            }else{
                header('location: /login');
            }
        }
    
    /* AVATAR VIEW  */
    /* ====================================================== */
        /*
         * 
         */

    public function avatarPic($data) {
				$id_encrypt = md5(md5($data['id']));
        $path = 'images/uploads/user_photos/' . $id_encrypt . '';
        
				if(is_dir($path)){
            $img = '<img data-placement="bottom" data-original-title="' . $data['title'] . '" src="/images/uploads/user_photos/' . $id_encrypt . '/' . $data['size'] . '_' . $id_encrypt . '.png" width="' . $data['width'] . '" height="' . $data['height'] . '" class="img-file-' . $id_encrypt . ' ' . $data['class'] . ' userAvatar" ' . $data['style'] . '>';
        } else {
            $img = '<img data-placement="bottom" data-original-title="' . $data['title'] . '" src="/images/avatar/avatar.png" width="' . $data['width'] . '" height="' . $data['height'] . '" class="img-file-' . $id_encrypt . ' ' . $data['class'] . ' userAvatar" ' . $data['style'] . '>';
        }
        return $img;
    }
}


?>